/*
 * @Author: jlgit jlgit@itcode.cn
 * @Date: 2023-09-13 16:37:39
 * @LastEditors: jlgit jlgit@itcode.cn
 * @LastEditTime: 2023-09-14 14:09:42
 * @FilePath: \jl-shopping\src\router\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import Myorder from '@/views/myorder'
import Pay from '@/views/pay'
import Search from '@/views/search'
import SearchList from '@/views/search/list'
import Prodetail from '@/views/prodetail'
import Home from '@/views/layout/home'
import Cart from '@/views/layout/cart'
import Category from '@/views/layout/category'
import User from '@/views/layout/user'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      { path: '/home', component: Home },
      { path: '/cart', component: Cart },
      { path: '/category', component: Category },
      { path: '/user', component: User }
    ]
  },
  { path: '/myorder', component: Myorder },
  { path: '/pay', component: Pay },
  { path: '/search', component: Search },
  { path: '/searchlist', component: SearchList },
  // 商品详情 动态路由
  { path: '/prodetail/:id', component: Prodetail }
]

const router = new VueRouter({
  routes
})
// 所有路由在真正访问之前都会经过全局前置守卫
// 1. to  往哪里去， 到哪去的路由信息对象
// 2. from 从哪里来， 从哪来的路由信息对象
// 3. next() 是否放行
//    如果next()调用，就是放行
//    next(路径) 拦截到某个路径页面

// 定义个数组 ，专门存放所有需要权限才能访问的
const authUrls = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  // console.log(to, from, next)
  if (!authUrls.includes(to.path)) {
    next()
    return
  }
  // 是权限页面
  const token = store.getters.token
  // console.log(token)
  if (token) {
    next()
  } else {
    next('/login')
  }
})
export default router
